<template>
  <div class="content">
    <el-button type="primary" @click="handleAddRole">+ 添加角色</el-button>
    <!-- 角色抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="30%" direction="rtl">
      <el-form class="form-inline" :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="formData.state">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="form-button">
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 菜单权限分配弹窗 -->
    <el-dialog v-model="menuDialogVisible" :title="menuDialogTitle" width="600px">
      <div class="menu-permission-container">
        <div class="menu-actions">
          <el-button @click="expandAll">全部展开</el-button>
          <el-button @click="collapseAll">全部收起</el-button>
          <el-button @click="checkAll">全部选择</el-button>
          <el-button @click="uncheckAll">全部取消</el-button>
        </div>
        <el-tree ref="menuTreeRef" :data="menuTreeData" show-checkbox node-key="id" :props="treeProps"
          :default-checked-keys="checkedMenuKeys" :filter-node-method="filterNode" class="menu-tree">
          <template #default="{ node }">{{ node.label }}</template>
        </el-tree>
        <div class="dialog-actions">
          <el-button type="primary" @click="submitMenuPermission">提交</el-button>
          <el-button @click="menuDialogVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 角色表格 -->
    <el-table :data="dataList" style="width: 100%;margin-top: 20px;" row-key="id">
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="state" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.state === 0 ? 'success' : 'danger'">
            {{ row.state === 0 ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="success" @click="handleMenuPermission(row)">菜单权限</el-button>
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 40, 50, 100]" :page-size="pageSize" :current-page="currentPage"
        layout="total, prev, pager, next, sizes, jumper" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import type { ElTree } from 'element-plus'
import { getAllRolesAPI, addRoleAPI, updateRoleAPI, deleteRoleAPI, bindMenuAPI, getRoleMenuListAPI } from '@/api/role'
import { getTreeMenuAPI } from '@/api/menu'
import type { RoleItem, MenuItem } from '@/types'

// 角色数据
const dataList = ref<RoleItem[]>([])

// 角色抽屉
const drawerVisible = ref(false)
const drawerTitle = ref('添加角色')
const isEdit = ref(false)

const formRef = ref<FormInstance>()
const formData = reactive<RoleItem>({
  roleName: '',
  state: 0,
})

// 菜单权限弹窗
const menuDialogVisible = ref(false)
const menuDialogTitle = ref('分配菜单权限')
const menuTreeRef = ref<InstanceType<typeof ElTree> | null>(null)
const menuTreeData = ref<MenuItem[]>([])
const checkedMenuKeys = ref<string[]>([])
const currentRole = ref<RoleItem | null>(null)

// 树形配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 表单验证规则
const formRules: FormRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  state: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}
// 添加
const handleAddRole = () => {
  drawerTitle.value = '添加角色'
  isEdit.value = false
  handleReset()
  drawerVisible.value = true
}
// 编辑
const handleEdit = (row: RoleItem) => {
  drawerTitle.value = '编辑角色'
  isEdit.value = true
  Object.assign(formData, { ...row })
  drawerVisible.value = true
}
// 删除
const handleDelete = async (row: RoleItem) => {
  try {
    await ElMessageBox.confirm('确定删除该角色吗？', '提示', {
      type: 'warning'
    })
    await deleteRoleAPI(row.id!)
    ElMessage.success('删除成功')
    loadRoleList()
  } catch (error) {
    console.log("删除取消或出错:", error)
  }
}
// 菜单权限
const handleMenuPermission = async (row: RoleItem) => {
  currentRole.value = row
  menuDialogTitle.value = `分配 ${row.roleName} 的菜单权限`

  try {
    // 加载菜单树
    const menuResponse = await getTreeMenuAPI()
    if (menuResponse.code === 200) {
      menuTreeData.value = menuResponse.result || []
    }
    // 加载角色已绑定的菜单
    const roleMenuResponse = await getRoleMenuListAPI(row.id!)
    if (roleMenuResponse.code === 200) {
      checkedMenuKeys.value = roleMenuResponse.result.map((e: MenuItem) => e.id as string)
    }
    menuDialogVisible.value = true
  } catch (error) {
    console.error('加载菜单权限失败:', error)
    ElMessage.error('加载菜单权限失败')
  }
}
// 全部展开
const expandAll = () => {
  if (menuTreeRef.value) {
    // 使用更安全的方法展开所有节点
    const allNodes = document.querySelectorAll('.el-tree-node')
    allNodes.forEach((node: Element) => {
      const expandIcon = node.querySelector('.el-tree-node__expand-icon') as HTMLElement
      if (expandIcon && expandIcon.classList.contains('is-leaf')) {
        // 如果是叶子节点，跳过
        return
      }
      if (expandIcon && !node.classList.contains('is-expanded')) {
        expandIcon.click() // 模拟点击展开
      }
    })
  }
}

// 全部收起
const collapseAll = () => {
  if (menuTreeRef.value) {
    // 使用更安全的方法收起所有节点
    const expandedNodes = document.querySelectorAll('.el-tree-node.is-expanded')
    expandedNodes.forEach((node: Element) => {
      const expandIcon = node.querySelector('.el-tree-node__expand-icon') as HTMLElement
      if (expandIcon && !expandIcon.classList.contains('is-leaf')) {
        expandIcon.click() // 模拟点击收起
      }
    })
  }
}

// 全部选择
const checkAll = () => {
  if (menuTreeRef.value) {
    const allKeys = getAllMenuKeys(menuTreeData.value)
    menuTreeRef.value.setCheckedKeys(allKeys)
  }
}

// 全部取消
const uncheckAll = () => {
  if (menuTreeRef.value) {
    menuTreeRef.value.setCheckedKeys([])
  }
}

// 获取所有菜单键
const getAllMenuKeys = (menus: MenuItem[]): string[] => {
  let keys: string[] = []
  menus.forEach(menu => {
    if (menu.id) {
      keys.push(menu.id)
    }
    if (menu.children && menu.children.length > 0) {
      keys = keys.concat(getAllMenuKeys(menu.children))
    }
  })
  return keys
}

// 过滤节点
const filterNode = (value: string, data: MenuItem) => {
  if (!value) return true
  return data.name.includes(value)
}

// 提交菜单权限
const submitMenuPermission = async () => {
  if (!currentRole.value || !menuTreeRef.value) return

  try {
    await bindMenuAPI({
      roleId: currentRole.value.id!,
      menuIds: menuTreeRef.value.getCheckedKeys().map(e => e.toString())
    })
    ElMessage.success('菜单权限分配成功')
    menuDialogVisible.value = false
  } catch (error) {
    console.error('分配菜单权限失败:', error)
    ElMessage.error('分配菜单权限失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  try {
    if (isEdit.value) {
      await updateRoleAPI(formData)
      ElMessage.success('修改成功')
    } else {
      await addRoleAPI(formData)
      ElMessage.success('添加成功')
    }

    drawerVisible.value = false
    loadRoleList()
  } catch (error) {
    ElMessage.error('操作失败')
    console.log(error)
  }
}
// 重置表单
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    roleName: '',
    state: 0,
  })
}
// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  loadRoleList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadRoleList()
}
// 加载角色列表
const loadRoleList = async () => {
  try {
    const response = await getAllRolesAPI()

    if (response.code === 200) {
      dataList.value = response.result || []
      total.value = dataList.value.length
    } else {
      ElMessage.error(response.message || '加载失败')
    }
  } catch (error) {
    console.error('加载角色列表失败:', error)
    ElMessage.error('加载角色列表失败')
  }
}

// 初始化
onMounted(() => {
  loadRoleList()
})
</script>

<style scoped>
.content {
  width: 100%;
  height: 100%;
  font-size: 14px;
  background-color: #ffffff;
  padding: 20px;
}

.menu-permission-container {
  position: relative;
  max-height: 60vh;
  overflow-y: auto;
}

.menu-actions {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #ffffff;
  margin-bottom: 20px;
}

.dialog-actions {
  position: sticky;
  bottom: 0;
  z-index: 10;
  background-color: #ffffff;
  margin-top: 20px;
}

:deep(.el-table) {
  border: 1px solid #ebeef5;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #101010;
  font-weight: 600;
  text-align: center;
}

:deep(.el-table td) {
  padding: 12px 0;
  text-align: center;
}

:deep(.el-button) {
  margin-right: 8px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
